import Vue from 'vue'
import Vuex from 'vuex'
import list from '../mock/mock'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: list.list1,
    datas: list.list2,
    sclist: localStorage.getItem('sclist') ? JSON.parse(localStorage.getItem('sclist')) : [],//收藏列表
    addresslist: localStorage.getItem('addresslist') ? JSON.parse(localStorage.getItem('addresslist')) : [],//地址列表
    clicksc: localStorage.getItem('clicksc') ? JSON.parse(localStorage.getItem('clicksc')) : []//默认收藏项
  },
  mutations: {
    // 地址列表
    addAddress(state, payload) {
      if (payload.name && payload.phone && payload.address && payload.housenum) {
        state.addresslist.push(payload)
      } else {
        alert('内容不能为空')
      }
      localStorage.setItem('addresslist', JSON.stringify(state.addresslist))
    },
    //修改地址
    redactAddress(state, payload) {
      let ind = state.addresslist.findIndex(item => {
        return item.id === payload.id
      })
      if (payload.name && payload.phone && payload.address && payload.housenum) {
        state.addresslist.splice(ind, 1, payload)
      } else {
        alert('内容不能为空')
      }
      localStorage.setItem('addresslist', JSON.stringify(state.addresslist))
    },
    //点击保存默认地址
    clicksave(state, payload) {
      state.clicksc = payload
      localStorage.setItem('clicksc', JSON.stringify(state.clicksc))
    },

    //点击添加收藏
    collect(state, payload) {
      let itemIn = state.sclist.findIndex(item => {
        return item.id === payload.id
      })
      if (itemIn === -1) {
        state.sclist.push(payload)
      }
      localStorage.setItem('sclist', JSON.stringify(state.sclist))
    },
    //点击取消收藏
    cancal(state, payload) {
      let itemIn = state.sclist.findIndex(item => {
        return item.id === payload.id
      })
      if (itemIn !== -1) {
        state.sclist.splice(itemIn, 1)
      }
      localStorage.setItem('sclist', JSON.stringify(state.sclist))
    },
    //清空收藏列表
    empty(state) {
      state.sclist.splice(0, state.sclist.length)
      localStorage.setItem('sclist', JSON.stringify(state.sclist))
    }
  },
  actions: {
  },
  modules: {
  }
})
